package com.haochang.chunkvod.app.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.tools.vod.log.Logger;

import android.text.TextUtils;

/**
 * @author qintao
 *         created at 2016/7/25 15:04
 *         购物车GoodsInfoList通过口味属性合并数据
 */

public class JoinListUtils
{
	/**
	 * 口味相同的商品合并数据
	 *
	 * @param infoList
	 * @return
	 */
	public static List<GoodsInfo> joinDataList(List<GoodsInfo> infoList)
	{
		List<GoodsInfo> joinList = new ArrayList<GoodsInfo>();
		//合并相同口味的数据
		for (GoodsInfo goodInfo : infoList)
		{
			boolean state = false;
			for (GoodsInfo info : joinList)
			{
				if (TextUtils.equals(info.getFlavor(), goodInfo.getFlavor()))
				{
					int num = info.getOrderNum();
					num += goodInfo.getOrderNum();
					info.setOrderNum(num);
					if (goodInfo.getId() > 0)//id>0表示从数据库查询的
						info.setId(goodInfo.getId());
					state = true;
				}
			}
			if (!state)
			{
				joinList.add(goodInfo);
			}
		}
		return joinList;
	}

	/**
	 * 商品详情口味相同的商品合并数据
	 * @param jsonArray
	 * @return
	 */
	public static JSONArray joinDataJsonArray(JSONArray jsonArray)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < jsonArray.length(); i++)
		{
			JSONObject obj = jsonArray.optJSONObject(i);
			String flavor = obj.optString("flavor");
			int number = obj.optInt("number");
			String num1 = map.get(flavor);
			if (TextUtils.isEmpty(num1))
			{
				map.put(flavor, String.valueOf(number));
			} else
			{
				int num2 = Integer.parseInt(num1);
				map.put(flavor, String.valueOf(number + num2));
			}
		}
		JSONArray joinArray = new JSONArray();
		for (String key : map.keySet())
		{
			JSONObject jsonObject = new JSONObject();
			try
			{
				jsonObject.put("flavor", TextUtils.isEmpty(key) ? new JSONArray() : new JSONArray(key));
				jsonObject.put("number", map.get(key));
				joinArray.put(jsonObject);
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
		return joinArray;
	}
}
